import { Key, useEffect, useState } from "react";
import { useModal } from "../useModal";
import { useModel } from "../factory";
import { useForm } from "../useForm";
import { SysRole } from "@sker/model";
import { useProTable } from "../useTable";
import { Button, Card, Dropdown, Modal, Popconfirm } from "antd";
import { BetaSchemaForm } from "@ant-design/pro-form";
import { PlusOutlined } from "@ant-design/icons";
import { ProTable } from "@ant-design/pro-components";

export const SysRoleSelector: React.FC<{ multi?: boolean, value?: Key[], onSelect: (record: any) => void }> = ({ value, multi, onSelect }) => {
    const { props: modalProps, setOpen } = useModal('添加角色')
    const model = useModel(SysRole)
    const { props: formProps, form } = useForm([
        { title: '角色名', dataIndex: 'title', formItemProps: { rules: [{ required: true, message: '请输入角色名' }] } },
        { title: '简介', dataIndex: 'desc', valueType: 'textarea' }
    ], async (values) => {
        if (editRecord) {
            values.id = editRecord.id;
        }
        await model.save(values, ['id'])
        setOpen(false);
        setEditRecord(null)
        await actionRef.current?.reload();
    })
    const [editRecord, setEditRecord] = useState<any>()
    const { props: proTableProps, selectedRows, selectedRowKeys, actionRef, setSelectedRows, setSelectedRowKeys } = useProTable(multi ? 'checkbox' : 'radio', value);
    useEffect(() => {
        if (!editRecord) {
            form.resetFields();
            return
        };
        form.setFieldsValue(editRecord)
    }, [editRecord])
    useEffect(() => {
        if (selectedRows && selectedRows.length > 0) {
            onSelect(selectedRows[0])
        }
    }, [selectedRows])
    return <>
        <Modal {...modalProps}>
            <BetaSchemaForm {...formProps} />
        </Modal>
        <Card title={'角色管理'} extra={<Button type={'primary'} size="small" icon={<PlusOutlined />} onClick={() => {
            setEditRecord(null)
            setOpen(true)
        }}></Button>} >
            <ProTable
                rowKey={record => record.id}
                request={async () => {
                    return model.find(['id', 'rid', 'title', 'desc'], [], [{ field: 'rid', order: 'desc' }]).then(res => {
                        const items = res.data.filter(it => selectedRowKeys.includes(it.id))
                        setSelectedRows(items)
                        if (!value && res.data.length > 0) {
                            setSelectedRows([res.data[0]])
                            setSelectedRowKeys([res.data[0].id])
                        }
                        return res;
                    })
                }}
                columns={[
                    { title: '序', dataIndex: 'rid' },
                    { title: '名称', dataIndex: 'title' },
                    { title: '简介', dataIndex: 'desc' },
                    {
                        title: '操作',
                        align: 'right',
                        render: (dom, entity, index, action, schema) => {
                            return <>
                                <Button size={'small'} type={'link'} onClick={e => {
                                    setOpen(true)
                                    setEditRecord(entity)
                                }}>编辑</Button>
                                <Popconfirm onConfirm={async e => {
                                    await model.delete(entity.id)
                                    await actionRef.current?.reload();
                                }} title={'此操作不可逆!您确定要执行此操作吗？'} description={'删除后无法恢复，请慎重操作！！'}>
                                    <Button size={'small'} type={'link'} danger>删除</Button>
                                </Popconfirm>
                            </>
                        }
                    },
                ]}
                {...proTableProps}
            ></ProTable>
        </Card>
    </>
}